package com.my.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.demo.pojo.EnterpriseSpace;
import com.my.demo.pojo.EnterpriseUser;
import com.my.demo.pojo.Result;
import com.my.demo.service.EnterpriseSpaceService;
import com.my.demo.service.EnterpriseUserService;
import com.my.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class CreateEnterpriseSpaceController {
    @Autowired
    EnterpriseSpaceService enterpriseSpaceService;
    @Autowired
    EnterpriseUserService enterpriseUserService;
    @Autowired
    UserService userService;

    //创建企业空间
    @PostMapping("create_enterprise_space")
    public Result createEnterpriseSpace(@RequestBody Map<String,String> map){
        Result result = new Result<>();
        result.setSuccess(false);
        result.setMsg(null);

        Integer userId=null;
        try {
            String userName = (String) SecurityUtils.getSubject().getPrincipal();
            userId = userService.selectIdByName(userName);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        if (userId==null||userId<=0){
            return result;
        }

        String spaceName=map.get("spaceName");
        try {
            spaceName=map.get("spaceName");
        }catch (Exception exception){
            exception.printStackTrace();
        }
        if (spaceName==null||spaceName.equals("")){
            return result;
        }

        try {
            //更新EnterpriseSpace表
            EnterpriseSpace enterpriseSpace=new EnterpriseSpace(userId,spaceName);
            enterpriseSpaceService.save(enterpriseSpace);
            Integer spaceId=enterpriseSpace.getSpaceNo();
            result.setSuccess(true);

            QueryWrapper<EnterpriseSpace> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("creator",userId);
            queryWrapper.eq("space_name",spaceName);

            //更新EnterpriseUser表
            enterpriseUserService.save(new EnterpriseUser(spaceId,userId,1));

            return result;
        }catch (Exception exception){
            exception.printStackTrace();
        }

        return result;
    }
}
